

'''

返回api任务websocket

'''

import websocket,json,sys
# 加入项目目录
sys.path.append('../')

from common.Helper import Helper
from common.config import *
from threading import Thread
from runserver import RequestTask



try:

    import thread

except ImportError:

    import _thread as thread

import time

# 全局锁

# l = threading.Lock()

# mac地址
# 公网当前ip
# 机器码
# 线程锁
#

exitFlag = 0

def on_message(ws, message):

    pass


def on_error(ws, error):

    pass


def on_close(ws):

    exitFlag = False

    on_open( ws ,exitFlag)

    print("*------------------Websocket【API】链接平台----------------*")

    # 如果websocket连接失败 每间隔5秒进行一次请求
    time.sleep(5)

    main()


def on_open(ws,condition=True):

    r = RequestTask()

    if condition:

        print('*------------------Websocket【API】链接平台---------------------*')

        # 机器码进行验证 type 类型4
        ws.send(Helper.privateInfo( 4 ))

        def run(types):

            while True:

                data = r.receTask(types)

                if data:

                    data = Helper.changeBase64( json.dumps(data) ).decode('ascii')

                    ws.send( data )

                    time.sleep(2)

        #心跳包验证
        def heartPack(*args):

            while True:

                data = {

                    'type': 9,
                    'content': (Helper.changeBase64(json.dumps({'count':0}))).decode('ascii')

                }

                # 加密
                data = Helper.changeBase64(json.dumps(data))

                ws.send(data)

                time.sleep(59)

        # 发送消息

        threads = []
        # api接口任务
        for i in range(3):

            t = Thread( target=run,args=('api_tasks',))

            t.start()

            threads.append( t )

        [ t.join() for t in threads ]

        #心跳包数据
        Thread( target=heartPack,args=()).start()

def main():

    websocket.enableTrace(False)

    ws = websocket.WebSocketApp( ws_connect,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)

    ws.on_open = on_open

    ws.run_forever(ping_interval=30, ping_timeout=5)

if __name__ == '__main__':

    main()